import DetectFace, { IDetectFace } from '@xmov/detect-face'

interface IWakeUpOptions {
  noFace_callback: () => void
  hasFace_callback: (faceArr: any) => void
  faceStart_callback?: () => void
  faceError_callback?: (err: string) => void
}

export default class FaceAndAudioCallback {
  private options: IWakeUpOptions
  private detectFace: IDetectFace
  private total = 15
  private delay = 1000
  private count = 0
  private timer: any = null
  private longTimeNoFace = true // 默认未检测到人脸

  constructor(options: IWakeUpOptions) {
    this.options = options
    this.detectFace = new DetectFace({
      modelType: 'tinyFaceDetector',
    })
    this.detectFace.setup().then(() => {
      this.onFaceStart()
    }).catch((err: any) => {
      this.onFaceError(err)
    })
  }

  creatTimer() {
    this.checkFace(this.total)
    this.removeTimer()
    this.timer = setTimeout(() => {
      this.creatTimer()
    }, this.delay)
    // }, this.longTimeNoFace ? 1000 : this.delay)
  }

  removeTimer() {
    if (this.timer) {
      clearTimeout(this.timer)
    }
    this.timer = null
  }

  private async checkFace(total: number) {
    const faceArr = await this.detectFace.getAllFaces()
    if (faceArr && faceArr.length > 0) {
      this.count = 0
      this.onFaceSuccess(faceArr)
    } else {
      this.count++
      if (this.count >= total) {
        this.count = 0
        this.onLongTimeNoFace()
      }
    }
  }

  reCountTime() {
    this.count = 0
  }

  private onLongTimeNoFace() {
    this.longTimeNoFace = true
    this.options.noFace_callback()
  }

  private onFaceStart() {
    if (typeof this.options.faceStart_callback === 'function') {
      this.options.faceStart_callback()
    }
  }

  private onFaceError(err: any) {
    if (typeof this.options.faceError_callback === 'function') {
      this.options.faceError_callback(err)
    }
  }

  private onFaceSuccess(faceArr: any) {
    if (!this.longTimeNoFace) {
      return
    }
    this.longTimeNoFace = false
    this.options.hasFace_callback(faceArr)
  }

  reset() {
    this.longTimeNoFace = true
  }

  close() {
    this.removeTimer()
    this.detectFace.close()
  }
}
